/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/admin/categories/post',
    updateUrl: '/admin/categories/put',
    deleteUrl: '/admin/categories/delete',
    selectUrl: '/admin/categories/get'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

$().ready(function () {
    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $.ajax(
        {
            url: Config.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function(category){
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true" ');
                    if (parentCategoryIdChecked == category.categoryId){
                        categories.push('selected="selected">');
                    }else{
                        categories.push('>');
                    }
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#parentCategoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $('#submitCategoryCreate').click( function() {
        $("#ajaxform").validate();
        if ($('#ajaxform').valid()){
            var postData = $('#ajaxform').serializeArray();
            $.ajax(
                {
                    url : Config.updateUrl,
                    type: "PUT",
                    data : postData,
                    dataType: "json",
                    success:function(data, textStatus, jqXHR)
                    {
                        toastr.success(data.msg, data.title);
                    },
                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });

    $('#buttonGoback').click(function() {
        history.go(-1);
        location.reload();
        return false;
    });
});
